import { getcharm } from "../../utils/api";
Page({
  data: {
    scan: false,
    photograph: false,
    src: "",
  },
  switch_scan() {
    this.setData({
      scan: !this.data.scan,
    });
  },
  open_album() {
    wx.chooseImage({
      count: 1,
      sizeType: ["original"],
      sourceType: ["album"],
      success: (result) => {
        this.get_data(result.tempFilePaths[0]);
      },
    });
  },
  open_camera() {
    this.setData({
      photograph: true,
    });
  },
  takePhoto() {
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: "high",
      success: (res) => {
        this.setData({
          photograph: false,
        });
        this.get_data(res.tempImagePath);
      },
    });
  },
  get_data(src) {
    this.setData({
      src,
    });
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    // let base64 = wx
    //   .getFileSystemManager()
    //   .readFileSync(src, "base64");
    // console.log(base64);
    wx.getFileSystemManager().readFile({
      filePath: src,
      encoding: "base64",
      success: (res) => {
        let base64 = "data:image/jpeg;base64," + res.data;
        getcharm({
          data: {
            imgbase64: base64,
          },
          method: "POST",
          success: (res) => {
            wx.hideLoading();
            console.log(res);
            if (res.data.Age) {
              wx.navigateTo({
                url: "/pages/success/success",
                success: (result) => {
                  result.eventChannel.emit(
                    "homeEvent",
                    res.data,
                    this.data.src
                  );
                  this.setData({
                    scan: false,
                    src: "",
                  });
                },
              });
              wx.showToast({
                title: "扫描完成",
                icon: "success",
                duration: 2000,
              });
            } else {
              wx.showToast({
                title: "扫描出错",
                duration: 2000,
              });
              this.setData({
                scan: false,
                src: "",
              });
            }
          },
          fail: (err) => {
            console.log(err);
            wx.hideLoading();
            wx.showToast({
              title: "失败",
              icon: "warn",
              duration: 2000,
            });
          },
        });
      },
    });
  },
});
